﻿using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace ConsoleAppFramework.Rmq
{
    public abstract class RmqOneMsgComsumerWorkerBase<T>
    {
        protected RmqUrlEnum RmqUrl { get; set; }

        protected string QueueName { get; set; } = "";


        protected bool FailEnqueue { get; set; }

        public void HandleOneMessage()
        {
            bool flag = true;
            T val = default(T);
            try
            {
                RmqConnect connect = RmqConnectPoolFactory.GetClientPool(RmqUrl).GetConnect();
                try
                {
                    BasicGetResult basicGetResult = null;
                    using (IModel model = connect.GetChannel())
                    {
                        basicGetResult = model.BasicGet(QueueName, autoAck: true);
                    }

                    if (basicGetResult != null)
                    {
                        val = JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(basicGetResult.Body));
                        flag = HandleComingMessage(val);
                    }
                }
                catch (Exception ex)
                {
                    flag = false;
                    RmqLogHelper.WriteError("RmqOneMsgComsumerWorkerBase消费队列异常(内部)：" + ex.Message);
                }
                finally
                {
                    if (FailEnqueue && !flag)
                    {
                        new RmqFailService(QueueName, RmqUrl).FailSend(val);
                    }
                }
            }
            catch (Exception ex2)
            {
                RmqLogHelper.WriteError("RmqOneMsgComsumerWorkerBase消费队列异常：" + ex2.Message);
            }
        }

        protected abstract bool HandleComingMessage(T messageDTO);
    }
}
